package com.aliyun.product.server.service;

import com.aliyun.commons.model.Result;
import com.aliyun.commons.service.CacheService;
import com.aliyun.product.client.model.ProductDTO;
import com.aliyun.product.client.service.ProductService;
import com.aliyun.product.server.dao.entity.ProductDO;
import com.aliyun.product.server.dao.mapper.ProductMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 商品服务实装
 *
 * 
 * @date 2024/11/27
 */
@DubboService
public class ProductServiceImpl implements ProductService {

    private static final String PRODUCT_CACHE_KEY = "PRODUCT_";

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private CacheService cacheService;

    @Override
    public Result<ProductDTO> getProduct(long productId) {
        String key = buildCacheKey(productId);
        ProductDO productDO = cacheService.getValue(key, ProductDO.class);
        if (productDO == null) {
            productDO = productMapper.selectById(productId);
            if (productDO != null) {
                // 永久缓存
                cacheService.setValue(key, productDO, 0);
            }
        }
        return Result.success(toProductDTO(productDO));
    }

    @Override
    public Result<Void> resetCache(Long productId) {
        cacheService.deleteKey(buildCacheKey(productId));
        getProduct(productId);
        return Result.success(null);
    }

    /**
     * 构建缓存键
     *
     * @param productId 商品 ID
     * @return {@link String }
     */
    private String buildCacheKey(long productId) {
        return PRODUCT_CACHE_KEY + productId;
    }

    /**
     * 转换商品 DTO
     *
     * @param productDO 商品实体
     * @return {@link ProductDTO }
     */
    private ProductDTO toProductDTO(ProductDO productDO) {
        if (productDO == null) {
            return null;
        }
        ProductDTO productDTO = new ProductDTO();
        productDTO.setId(productDO.getId());
        productDTO.setGmtCreate(productDO.getGmtCreate());
        productDTO.setTitle(productDO.getTitle());
        productDTO.setDescription(productDO.getDescription());
        productDTO.setPic(productDO.getPic());
        productDTO.setOriginalPrice(productDO.getOriginalPrice());
        productDTO.setStatus(productDO.getStatus());
        return productDTO;
    }
}